package com.eva.androidlibrary.widget.tabhost;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;

/**
 * Tab host + fragment
 *
 * @author GUXIA318
 * @date 2015-09-16 12:54
 */
public class FragmentTabHostLayout extends TabHostLayout {

    private FragmentTabHostLayoutAdapter mAdapter;
    private int mCurPosition = INVALID_POSITION;

    public FragmentTabHostLayout(@NonNull Context context) {
        super(context);
    }

    public FragmentTabHostLayout(@NonNull Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FragmentTabHostLayout(@NonNull Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setAdapter(TabHostLayoutAdapter adapter) {
        super.setAdapter(adapter);
        this.mAdapter = (FragmentTabHostLayoutAdapter) adapter;
    }

    public int getCurrentPosition() {
        return mCurPosition;
    }

    @Override
    protected void onTabChanged(int position) {
        super.onTabChanged(position);
        if (mCurPosition != position && mAdapter != null) {
            FragmentManager fm = mAdapter.getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();

            if (mCurPosition != INVALID_POSITION) {
                Fragment cur = fm.findFragmentByTag(String.valueOf(mCurPosition));
                if (cur != null) {
                    ft.hide(cur);
                }
            }

            Fragment f = mAdapter.getFragment(position);

            if (f != null) {
                if (!f.isAdded()) {
                    ft.add(mAdapter.getContainerView(), f, mAdapter.getFragmentTag(position));
                } else {
                    ft.show(f);
                }
            }
            ft.commit();
            mCurPosition = position;
        }
    }

}
